﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using L.Basic.Log;
using L.Manage;

namespace System.Web.Mvc
{
    /// <summary>
    /// 权限验证，针对当前登录用户，验证模块权限
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class LLogAttribute : FilterAttribute, IActionFilter
    {
        public string UserName { get; set; }
        public string UserId { get; set; }
        public string LoginIp { get; set; }

        public string LogType { get; set; }
        public string Message { get; set; }
        public string More { get; set; }

        /// <summary>
        /// 在执行完成以后，保存用户日志。比如：用户登录了；用户删除了xx数据等。
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            LogContent logContent = new LogContent()
                                        {
                                            UserId = UserId,
                                            UserName = UserName,
                                            LogType = LogType,
                                            Message = Message,
                                            More = More
                                        };
            logContent.Date = DateTime.Now;
            logContent.SessionId = filterContext.HttpContext.Session.SessionID;
            logContent.LoginIp = filterContext.HttpContext.Request.ServerVariables.Get("Remote_Addr").ToString();
            if (string.IsNullOrEmpty(logContent.More))
            {
                logContent.More = filterContext.HttpContext.Request.ServerVariables.NvcToString();
            }
            Log.Save(logContent);
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {

        }
    }

    public static class ToStringHelper
    {
        public static string NvcToString(this NameValueCollection nvc)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (String o in nvc)
            {
                stringBuilder.AppendFormat("{0}:{1};", o, nvc[o]);
            }
            return stringBuilder.ToString();
        }
    }
}
